(function(UI){
	//tmNodes 栏目信息
	var tmNodes = $.extend({}, workspaceVO.leftMenuNode);
	Ccay.Init.Complete.add(function(){
		topmenuInner.addDelegates($("#ccay_topMenu_show"));
		helper.buildTopMenu();
	});
	UI.TopMenu = {};
	var helper = UI.TopMenu.helper = {
		//构建menu的start方法
		buildTopMenu : function(){
			$("#ccay_topMenu_show").html(topmenuInner.buildMenuStr(true,null,"_tmL")).css("width",$(document.body).hasClass('fullScreen') ? "98%" : "980px");
			Ccay.Component.PushMsg.triggerByName();
			helper.endEvents();
		},
		/**@description 页面跳转后的操作，分点击菜单跳转，非点击菜单跳转
		 * @param clickHref 点击菜单的url
		 */
		endEvents : function(clickHref){
			if(topmenuInner.param.click2Forward){
				topmenuInner.param.click2Forward = false;
			}else{
				var url = window.location.href, ccayNode = Ccay.Page.getRequest().ccayNode;
				url.indexOf("#!") > -1 && (url = "#!" + url.split("#!")[1]);
				helper.getNodesQueue(tmNodes, ccayNode ? "location" : "url", ccayNode || url, "_tmL-1");
				if(topmenuInner.param.currentNodeId == ""){
					return;
				}
				//如果为首页
				if(topmenuInner.param.currentNodeId.lastIndexOf("-1") != topmenuInner.param.currentNodeId.length - 2){
					topmenuInner.param.currentNodeId = topmenuInner.param.currentNodeId.replace("-1_","");
				}
				topmenuInner.buildTreeArr(topmenuInner.param.currentNodeId);
			}
			topmenuInner.dealMenu();
		},
		/**
		 * @description 通过url访问时，将树的信息保存起来
		 * @param nodes 节点集合
		 * @param condition 查询条件
		 * @value 查询条件的值
		 * @index 返回的id的前缀
		 */
		getNodesQueue : function(nodes, condition, value , index) {
			topmenuInner.param.currentNodeId = nodes[condition] == value ? index : "";
			if(nodes.children){
				$.each(nodes.children,function(i,val){
					if(topmenuInner.param.currentNodeId){
						return false;
					}
					helper.getNodesQueue(val, condition, value, index + "_" + i);
				});
			}
		}
	};
	var topmenuInner = {
		/**
		 * @param paddingHeight 如果你修改了子层div的上下padding和上下border宽度，请修改以下值，上下padding+上下border宽度
		 * @param scrollWidth 滚动条的宽度
		 */
		config : {
			paddingHeight : 12,
			scrollWidth : 15
		},
		/**：
		 * @param cacheId,cacheId2,cacheId2  timeOut的缓存id
		 * @param containHeight 容器宽度
		 * @param nodesQueue 节点树队列
		 * @param destroy 是否关闭展示的菜单
		 * @param click2Forward 是够通过点击菜单项跳转
		 * @param divsQueue 当前展现的div的队列
		 * @param currentNodeId 当前url对应的node的id
		 */
		param : {
			cacheId : "",
			cacheId2 : "",
			cacheId3 : "",
			containHeight : $("#ccay_topMenu_show").outerHeight(),
			currentNodeId : "",
			nodesQueue :  [],
			divsQueue : [],
			destroy : false,
			click2Forward : false
		},
		/**
		 * @param root 是否为root层
		 * @nodes 节点集合
		 * @pIndex 生成的li的id的关联前缀
		 */
		buildMenuStr : function(root,nodes,pIndex){
			var divClass = 'topmenu-other-level', liClass = 'topmenu-item-li';
			root && (divClass = 'topmenu-root-level') && (liClass = 'topmenu-root-li');
			var strArr = ['<div class="'+divClass+'"><ul>'],
				temp = '<li id = "${#siteNodeId}" class = "'+liClass+'"><a title = "${#name}"${#aClass}${#href} target = "${#target}">${#name}</a></li>';
			//如果为root层，先保存首页，然后将children存放到nodes中
			if(root && tmNodes && tmNodes.children){
				tmNodes.href = tmNodes.url ? ' href ="'+tmNodes.url+'"' : '';
				tmNodes.siteNodeId = "_tmL-1";
				strArr.push(temp.formatField(tmNodes));
				nodes = tmNodes.children
			}
			$.each(nodes,function(i,node){
				node.aClass = (!root && node.children) ? ' class="lefttriangle"' : '';
				node.href = node.url ? ' href ="'+ node.url +'"' : '';
				node.siteNodeId = pIndex + (root? i: '_'+i);
				strArr.push(temp.formatField(node));
			})
			strArr.push('</ul></div>');
			return strArr.join('');
		},
		//处理访问之后的菜单其他相关信息，如：导航条，高亮显示，网页title
		dealMenu : function(){
			//导航条
			var nav = "_>";
			$.each(topmenuInner.param.nodesQueue,function(i,val){
				nav += val.url ? '&nbsp;&gt;<a href = "${#url}" target = "${#target}">${#text}</a>'.formatField(val) : '&nbsp;&gt;<span>${#text}</span>'.formatField(val);
			});
			$("#ccay_page_nav").html(nav.replace('_>&nbsp;&gt;',''));
			//title
			document.title = topmenuInner.param.nodesQueue[topmenuInner.param.nodesQueue.length-1].text+" - " +$i18n("app.common.label.title");
			//高亮显示root层
			$(".presentSelected").removeClass("presentSelected");
			$("#_tmL"+topmenuInner.param.nodesQueue[0].id).addClass("presentSelected").removeClass("present");
		},
		/**@description 点击后的操作事项
		 * @param href 菜单url
		 * @param id 菜单id
		 */
		stopDefaultEvent : function(href, id){
			$(".topmenu-other-level").remove();
			//if判断是否为点击节点为当前节点
			topmenuInner.param.click2Forward = true;
			topmenuInner.buildTreeArr(id);
			href==window.location.hash && Ccay.Page.forward(href);
		},
		//根据id创建当前节点的树关系链
		buildTreeArr : function (id){
			topmenuInner.param.nodesQueue = [];
			if(id.indexOf("-1") > 0){
				topmenuInner.param.nodesQueue.push({'id': '-1','text': tmNodes.name, 'url': tmNodes.url||null, 'target': tmNodes.target});
			}else{
				var nodes = tmNodes;
				$.each(id.replace("_tmL","").split("_"),function(i,val){
					nodes = nodes.children[val];
					topmenuInner.param.nodesQueue.push({'id':val ,'text': nodes.name, 'url': nodes.url||null, 'target': nodes.target});
				});
			}
		},
		//root层li获得焦点后事件
		onHover : function(hoverDom){
			//移除所有的非一级菜单
			$(".topmenu-other-level").remove();
			//childId 子div的id
			var hoverDomId = hoverDom.attr("id"),
				childId = "_d"+hoverDomId,
				JchildId = "#"+childId,
				pPosition = hoverDom.position(),
				index = hoverDomId.replace("_tmL","");
				children = index < 0 ? null :tmNodes.children[hoverDomId.replace("_tmL","")].children;
			//如果没有子菜单 或 已经生成子div了
			if(!children || $(JchildId).length){
				return;
			}
			//存放激活的菜单页
			topmenuInner.param.divsQueue = [hoverDomId,childId];
			//构造的html代码
			$("#ccay_topMenu_show").append($(topmenuInner.buildMenuStr(false,children, hoverDomId)).attr("id",childId).fadeIn(50));
			//我的待办任务推送，仅限‘我的待办任务’
			Ccay.Component.PushMsg.triggerByName();
			/* heightSpace 一级菜单底部一下的高度
			 * */
			var heightSpace = $(window).height() - topmenuInner.param.containHeight - $("#ccay_topMenu_show").position().top, child = $(JchildId);
			if(child.outerHeight() > heightSpace){
				child.height(heightSpace - topmenuInner.config.paddingHeight).css({"overflow-y" : "auto","overflow-x" : "hidden"});
			}
			var left = pPosition.left + child.outerWidth() > $(window).width() ? $(window).width() - child.outerWidth() : pPosition.left;
			child.css({"top" : pPosition.top + hoverDom.outerHeight(),"left" : left});
		},
		//其它层li获得焦点事件
		onHoverOther : function(pLi){
			/* childId 标记生成的div的id
			 * pPosition 父li的位置
			 * parentDivPosition 父div的位置
			 * children 父li所对应的children节点集合
			 * html 构造的子div的html代码
			 */
			var pLiId = pLi.attr("id"),
				childId = "_d"+pLi.attr("id"),
				jChildId = "#"+childId,
				pPosition = pLi.position(),
				pDiv = pLi.closest("div"),
				pDivPosition = pDiv.position(),
				children = tmNodes;
			$.each(pLiId.replace("_tmL","").split("_"),function(i,val){
				children = children.children[val];
			});
			children = children.children;
			
			//如果没有子菜单 或 已经生成子div了
			if(!children || $(jChildId).length){
				return;
			}
			var index = $.inArray(pDiv.attr("id"),topmenuInner.param.divsQueue);
			if(index > -1 && index != topmenuInner.param.divsQueue.length-1){
				for(var i = topmenuInner.param.divsQueue.length; i >index;i--){
					$("#"+topmenuInner.param.divsQueue[i]).remove();
				}
				topmenuInner.param.divsQueue = topmenuInner.param.divsQueue.slice(0,index + 1);
			}
			topmenuInner.param.divsQueue.push(childId);
			$("#ccay_topMenu_show").append($(topmenuInner.buildMenuStr(false,children,pLiId)).attr("id",childId).fadeIn(50));
			/* leftPosition  定义left,top坐标,由于需要取得html的高度，在append后定义position
			 * childHeight 定义scroll
			 * heightSpace 一级菜单底部一下的高度
			 */
			var leftPosition = pDivPosition.left + pDiv.outerWidth() - 1, childHeight = $(jChildId).outerHeight(),
			heightSpace = $(window).height() - topmenuInner.param.containHeight - $("#ccay_topMenu_show").position().top;
			if(childHeight > heightSpace){
				$(jChildId).height(heightSpace - topmenuInner.config.paddingHeight).css({"overflow-y" : "auto","overflow-x" : "hidden"});
			}
			if((leftPosition + $(jChildId).outerWidth()) > $(window).width()){
				leftPosition = leftPosition - pDiv.outerWidth() - $(jChildId).outerWidth() + 2;
			}
			//topSpace 为父li在其div中的top加上这个li的高度；topHeight为一级菜单的top加上一级菜单的高度
			var topHeight = $("#ccay_topMenu_show").position().top + topmenuInner.param.containHeight, topSpace = pPosition.top + 25 + pDivPosition.top - topHeight;
			//如果生成的div的高度小于topSpace。。。
			var	topPosition = (topSpace > childHeight) ?  topHeight + topSpace - childHeight + 8 : topHeight;
			$(jChildId).css({"top" : topPosition,"left" : leftPosition});
		},
		//代理事件集合
		addDelegates : function(j){
			j.undelegate().delegate(".topmenu-root-li,.topmenu-item-li", "click", function(){
				var aTag = $(this).find("a");
				aTag.attr("href") && topmenuInner.stopDefaultEvent(aTag.attr("href"), $(this).attr("id"));
			}).delegate(".topmenu-root-li", "mouseenter", function(){
				$(".present").removeClass("present");
				var hoverLi = $(this);
				topmenuInner.param.cacheId = setTimeout(function(){topmenuInner.onHover(hoverLi);},400);
			}).delegate(".topmenu-root-li", "mouseleave", function(){
				clearTimeout(topmenuInner.param.cacheId);
			}).delegate(".topmenu-other-level", "mouseenter",function(){
				$(".present").removeClass("present");
				$(".first-level-li-selected").removeClass("first-level-li-selected");
				var pLi = $("#"+$(this).attr("id").replace("_d",""));
				while (pLi){
					//回归高亮显示
					pLi.addClass(pLi.hasClass("topmenu-root-li") ? "present" : "first-level-li-selected")
					if(pLi.closest("div") && pLi.closest("div").hasClass("topmenu-other-level")){
						pLi = $("#"+pLi.closest("div").attr("id").replace("_d",""));
					}else{
						pLi = null;
					}
				}
			}).delegate(".topmenu-item-li","mouseenter",function(){
				var hoverLi = $(this);
				topmenuInner.param.cacheId2 = setTimeout(function(){
					topmenuInner.onHoverOther(hoverLi);
				}, 200);
			}).delegate(".topmenu-item-li","mouseleave",function(){
				clearTimeout(topmenuInner.param.cacheId2);
			});
			//失去焦点或者点击空白区域关闭菜单
			$("#ccay_topMenu_show,.topmenu-other-level").on("mouseover",function(){
				//兼容chrome
				$(this).attr("tabIndex",-1).focus();
				topmenuInner.param.destroy = false;
				clearTimeout(topmenuInner.param.cacheId3);
			}).on("mouseleave",function(){
				topmenuInner.param.destroy = true;
				//移出超过一段时间后菜单消失
				topmenuInner.param.cacheId3 = setTimeout(function(){
					if(topmenuInner.param.destroy){
						$(".topmenu-other-level").remove();
						$(".present").removeClass("present");
					}
				}, 1000);
			}).on("blur",function(){
				if(topmenuInner.param.destroy){
					$(".topmenu-other-level").remove();
					$(".present").removeClass("present");
				}		
			});
		}
	};
})(Ccay.UI);